<?php


namespace App\Service;


use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class BaiduCensor
{
    // 百度内容审核接口

    // 提交审核地址前缀
    protected $preUrl    = 'https://aip.baidubce.com/rest/2.0/solution/v1/';
    protected $APIKey    = 'llWSaURIqOOtf44yrmytzhoL';
    protected $SecretKey = 'EUmxgIjGgXOneoRkavz3BVf6iRFwobLi';

    // 初始化操作
    public function __construct() { }

    // 图片审核（同步）
    public function image($file)
    {
        $url   = 'img_censor/v2/user_defined';
        $img   = file_get_contents($file);
        $img   = base64_encode($img);
        $bodys = ['image' => $img,];
        $res   = $this->request($url, $bodys);

        return $res;
    }

    // 文本审核（同步）
    public function text($text)
    {
        $this->throwIf(mb_strlen($text) >= 15000, '内容过长！');
        $this->throwIf(empty($text), '内容不能为空！');

        $url   = 'text_censor/v2/user_defined';
        $bodys = ['text' => $text];
        $res   = $this->request($url, $bodys);

        return $res;
    }

    // 音频（同步）
    public function voice($file)
    {
        // 后缀
        if(is_object($file)){
            $ext = strtolower($file->getClientOriginalExtension());  // 上传文件的后缀.
        } else{
            $ext = pathinfo($file, PATHINFO_EXTENSION);
        }
        $url   = 'voice_censor/v3/user_defined';
        $img   = file_get_contents($file);
        $img   = base64_encode($img);
        $bodys = ['base64' => $img, 'fmt' => $ext];
        $res   = $this->request($url, $bodys);

        return $res;
    }

    // 短视频（同步）
    public function video()
    {
        $url   = 'video_censor/v2/user_defined';
        $bodys = ['name' => "视频名称", 'extId' => "视频id", 'videoUrl' => "视频url地址",];
        $res   = $this->request($url, $bodys);

        return $res;
    }

    // 长视频（异步操作）
    public function submit()
    {
        $url   = 'video_censor/v1/video/submit';
        $bodys = ['name' => "视频名称", 'extId' => "视频id", 'videoUrl' => "视频url地址", 'noticeUrl' => "审核结论通知地址", 'frequency' => "抽帧频率"];
        $res   = $this->request($url, $bodys);

        return $res;
    }

    // 长视频 获取结果
    public function pull()
    {
        $url   = 'video_censor/v1/video/pull';
        $bodys = ['name' => "视频名称", 'extId' => "视频id", 'videoUrl' => "视频url地址",];
        $res   = $this->request($url, $bodys);

        return $res;
    }

    // 获取token 有效期为30天
    public function getToken()
    {
        // 是否有缓存
        $cookie_name  = 'baidu_censor_access_token';
        $access_token = Cache::get($cookie_name);
        if($access_token){
            return $access_token;
        }

        // 如果没有缓存 则会去百度获取
        //$AppID、$APIKey、$SecretKey
        $APIKey    = $this->APIKey;
        $SecretKey = $this->SecretKey;
        // 执行请求 获取 access_token
        $url  = "https://aip.baidubce.com/oauth/2.0/token?client_id=".$APIKey."&client_secret=".$SecretKey."&grant_type=client_credentials";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json']);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 要求结果为字符串且输出到屏幕上

        $response = curl_exec($curl);
        curl_close($curl);

        // 不知道是不是需要只有处理
        $response = json_decode($response, true);
        // 是否成功
        $error = $response['error'] ?? '';
        if(empty($error)){
            $access_token = $response['access_token'] ?? '';
            $expires_in   = $response['expires_in'] ?? '';
            // 保存为缓存
            // 因为请求回来，需要花费时间，所以缓存时间应该比过期时间少一点
            Cache::add($cookie_name, $access_token, $expires_in - 20);

            return $access_token;
        }

        return $response;
    }


    // 获取token 有效期为30天
    public function getToken2()
    {
        // 是否有缓存
        $access_token = Cache::get('baidu_ai_access_token');
        if($access_token){
            return $access_token;
        }

        // $AppID、$APIKey、$SecretKey
        $APIKey    = $this->APIKey;
        $SecretKey = $this->SecretKey;
        // 执行请求 获取 access_token
        $url   = "https://aip.baidubce.com/oauth/2.0/token?client_id=".$APIKey."&client_secret=".$SecretKey."&grant_type=client_credentials";
        $url   = "https://aip.baidubce.com/oauth/2.0/token";
        $param = ['client_id' => $APIKey, 'client_secret' => $SecretKey, 'grant_type' => 'client_credentials'];
        $res   = $this->request($url, $param);

        // 整理
        //var_dump($res);
        $response = json_decode($res, true);
        // 是否成功
        $error = $response['error'] ?? '';
        if(empty($error)){
            $access_token = $response['access_token'] ?? '';
            $expires_in   = $response['expires_in'] ?? '';
            // 保存为缓存
            // 因为请求回来，需要花费时间，所以缓存时间应该比过期时间少一点
            Cache::add('baidu_ai_access_token', $access_token, $expires_in - 20);

            return $access_token;
        }

        return $response;
    }


    // 请求操作
    protected function request($url = '', $param = '')
    {
        if(empty($url) || empty($param)){
            return false;
        }

        $curlPost = $param;
        $token    = $this->getToken();
        $postUrl  = $this->preUrl.$url.'?access_token='.$token;
        /*$postUrl  = $url;
        if(substr($url, 0, 4) != 'http'){
            $postUrl = $this->preUrl.$url.'?access_token='.$this->token;
        }*/

        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);


        // 已达到打开api qps请求限制
        // Open api qps request limit reached
        $response = json_decode($data, true);
        if(!empty($response['error_msg'])){
            if($response['error_msg'] == 'Open api qps request limit reached'){
                $response['error_msg'] = '已达到打开api qps请求资源已经用完，请续费！';
            }

            Log::debug('百度审核 | '.$url.' | '.json_encode($response, JSON_UNESCAPED_UNICODE));
            $this->throwIf(true, $response['error_msg'] ?? '内容不合规！', 400);
        } else{
            if($response['conclusionType'] == 1){
                // 合规
            } else{
                // 不合规
                // $response['msg']=$response['data'][0]['msg'];
                $this->throwIf(true, $response['data'][0]['msg'] ?? '内容不合规！');
            }
        }

        return $response;
    }

    // 结束程序
    // 抛出异常
    protected function throwIf($condition, $msg, $code = 400)
    {
        if($condition){
            throw new \RuntimeException($msg, $code);
        }
    }

}


